<template>
  <div v-if="modelValue" class="modal-overlay" @click="handleOverlayClick">
    <div class="apple-card modal-dialog large-dialog" @click.stop>
      <div class="apple-card__header">
        <h2 class="text-heading">用户统计信息</h2>
        <button 
          class="close-button apple-button apple-button--text"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <div class="apple-card__body">
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p class="text-body">加载统计数据...</p>
        </div>

        <div v-else-if="statistics" class="statistics-content">
          <!-- 用户概览 -->
          <div class="statistics-section">
            <h3 class="section-title">用户概览</h3>
            <div class="overview-cards">
              <div class="stat-card stat-card--primary">
                <div class="stat-icon">👥</div>
                <div class="stat-content">
                  <div class="stat-value">{{ statistics.user_counts.total }}</div>
                  <div class="stat-label">总用户数</div>
                </div>
              </div>
              
              <div class="stat-card stat-card--success">
                <div class="stat-icon">✅</div>
                <div class="stat-content">
                  <div class="stat-value">{{ statistics.user_counts.active }}</div>
                  <div class="stat-label">激活用户</div>
                </div>
              </div>
              
              <div class="stat-card stat-card--warning">
                <div class="stat-icon">⏸️</div>
                <div class="stat-content">
                  <div class="stat-value">{{ statistics.user_counts.inactive }}</div>
                  <div class="stat-label">未激活用户</div>
                </div>
              </div>
              
              <div class="stat-card stat-card--danger">
                <div class="stat-icon">🚫</div>
                <div class="stat-content">
                  <div class="stat-value">{{ statistics.user_counts.suspended }}</div>
                  <div class="stat-label">暂停用户</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 活跃度统计 -->
          <div class="statistics-section">
            <h3 class="section-title">活跃度统计</h3>
            <div class="activity-stats">
              <div class="activity-item">
                <div class="activity-label">最近30天活跃用户</div>
                <div class="activity-value">
                  <span class="activity-number">{{ statistics.user_counts.recent_active }}</span>
                  <span class="activity-percentage">
                    ({{ getActivePercentage() }}%)
                  </span>
                </div>
                <div class="activity-bar">
                  <div 
                    class="activity-fill"
                    :style="{ width: getActivePercentage() + '%' }"
                  ></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 部门分布 -->
          <div class="statistics-section">
            <h3 class="section-title">部门分布</h3>
            <div v-if="statistics.department_distribution.length > 0" class="distribution-list">
              <div 
                v-for="dept in statistics.department_distribution" 
                :key="dept.department"
                class="distribution-item"
              >
                <div class="distribution-info">
                  <div class="distribution-name">{{ dept.department }}</div>
                  <div class="distribution-count">{{ dept.count }} 人</div>
                </div>
                <div class="distribution-bar">
                  <div 
                    class="distribution-fill"
                    :style="{ width: getDepartmentPercentage(dept.count) + '%' }"
                  ></div>
                </div>
                <div class="distribution-percentage">
                  {{ getDepartmentPercentage(dept.count) }}%
                </div>
              </div>
            </div>
            <div v-else class="empty-distribution">
              <p class="text-caption">暂无部门分布数据</p>
            </div>
          </div>

          <!-- 角色分布 -->
          <div class="statistics-section">
            <h3 class="section-title">角色分布</h3>
            <div v-if="statistics.role_distribution.length > 0" class="distribution-list">
              <div 
                v-for="role in statistics.role_distribution" 
                :key="role.role"
                class="distribution-item"
              >
                <div class="distribution-info">
                  <div class="distribution-name">{{ role.role }}</div>
                  <div class="distribution-count">{{ role.count }} 人</div>
                </div>
                <div class="distribution-bar">
                  <div 
                    class="distribution-fill"
                    :style="{ width: getRolePercentage(role.count) + '%' }"
                  ></div>
                </div>
                <div class="distribution-percentage">
                  {{ getRolePercentage(role.count) }}%
                </div>
              </div>
            </div>
            <div v-else class="empty-distribution">
              <p class="text-caption">暂无角色分布数据</p>
            </div>
          </div>

          <!-- 状态分布图表 -->
          <div class="statistics-section">
            <h3 class="section-title">状态分布</h3>
            <div class="status-chart">
              <div class="chart-item">
                <div class="chart-segment chart-segment--active" :style="{ width: getStatusPercentage('active') + '%' }"></div>
                <div class="chart-label">
                  <span class="chart-color chart-color--active"></span>
                  激活 ({{ statistics.user_counts.active }})
                </div>
              </div>
              <div class="chart-item">
                <div class="chart-segment chart-segment--inactive" :style="{ width: getStatusPercentage('inactive') + '%' }"></div>
                <div class="chart-label">
                  <span class="chart-color chart-color--inactive"></span>
                  未激活 ({{ statistics.user_counts.inactive }})
                </div>
              </div>
              <div class="chart-item">
                <div class="chart-segment chart-segment--suspended" :style="{ width: getStatusPercentage('suspended') + '%' }"></div>
                <div class="chart-label">
                  <span class="chart-color chart-color--suspended"></span>
                  暂停 ({{ statistics.user_counts.suspended }})
                </div>
              </div>
              <div class="chart-item">
                <div class="chart-segment chart-segment--locked" :style="{ width: getStatusPercentage('locked') + '%' }"></div>
                <div class="chart-label">
                  <span class="chart-color chart-color--locked"></span>
                  锁定 ({{ statistics.user_counts.locked }})
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="apple-card__footer">
        <button 
          type="button"
          class="apple-button apple-button--secondary"
          @click="refreshStatistics"
          :disabled="loading"
        >
          {{ loading ? '刷新中...' : '刷新数据' }}
        </button>
        <button 
          type="button"
          class="apple-button apple-button--primary"
          @click="handleClose"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/users'

// Props
interface Props {
  modelValue: boolean
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 状态
const loading = ref(false)
const statistics = ref<any>(null)

// 加载统计数据
const loadStatistics = async () => {
  loading.value = true
  try {
    const response = await userApi.getUserStatistics()
    if (response.success) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

// 计算百分比函数
const getActivePercentage = () => {
  if (!statistics.value) return 0
  const total = statistics.value.user_counts.total
  const active = statistics.value.user_counts.recent_active
  return total > 0 ? Math.round((active / total) * 100) : 0
}

const getDepartmentPercentage = (count: number) => {
  if (!statistics.value) return 0
  const total = statistics.value.user_counts.total
  return total > 0 ? Math.round((count / total) * 100) : 0
}

const getRolePercentage = (count: number) => {
  if (!statistics.value) return 0
  const total = statistics.value.user_counts.total
  return total > 0 ? Math.round((count / total) * 100) : 0
}

const getStatusPercentage = (status: string) => {
  if (!statistics.value) return 0
  const total = statistics.value.user_counts.total
  const count = statistics.value.user_counts[status] || 0
  return total > 0 ? Math.round((count / total) * 100) : 0
}

// 刷新统计数据
const refreshStatistics = () => {
  loadStatistics()
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 点击遮罩关闭
const handleOverlayClick = () => {
  handleClose()
}

// 监听对话框打开
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    loadStatistics()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.large-dialog {
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  overflow: hidden;
  animation: modalSlideIn var(--duration-normal) var(--ease-out);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.apple-card__header {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-button {
  position: absolute;
  right: 0;
  padding: var(--spacing-xs);
  font-size: 18px;
  opacity: 0.6;
}

.close-button:hover {
  opacity: 1;
}

.apple-card__body {
  max-height: 70vh;
  overflow-y: auto;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--apple-gray-5);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--spacing-md);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.statistics-section {
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 1px solid var(--border-secondary);
}

.statistics-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--color-primary);
  font-size: 16px;
  font-weight: 600;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--spacing-md);
}

.stat-card {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  padding: var(--spacing-lg);
  border-radius: var(--radius-large);
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-secondary);
}

.stat-card--primary {
  background-color: rgba(0, 122, 255, 0.1);
  border-color: var(--color-primary);
}

.stat-card--success {
  background-color: rgba(52, 199, 89, 0.1);
  border-color: var(--color-success);
}

.stat-card--warning {
  background-color: rgba(255, 149, 0, 0.1);
  border-color: var(--color-warning);
}

.stat-card--danger {
  background-color: rgba(255, 59, 48, 0.1);
  border-color: var(--color-danger);
}

.stat-icon {
  font-size: 32px;
  opacity: 0.8;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.stat-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.activity-stats {
  padding: var(--spacing-lg);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-medium);
}

.activity-item {
  margin-bottom: var(--spacing-md);
}

.activity-label {
  font-size: 14px;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.activity-value {
  display: flex;
  align-items: baseline;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
}

.activity-number {
  font-size: 20px;
  font-weight: 600;
  color: var(--color-primary);
}

.activity-percentage {
  font-size: 12px;
  color: var(--text-secondary);
}

.activity-bar {
  height: 8px;
  background-color: var(--bg-tertiary);
  border-radius: 4px;
  overflow: hidden;
}

.activity-fill {
  height: 100%;
  background-color: var(--color-primary);
  transition: width var(--duration-normal) var(--ease-out);
}

.distribution-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.distribution-item {
  display: grid;
  grid-template-columns: 1fr 200px 60px;
  gap: var(--spacing-md);
  align-items: center;
  padding: var(--spacing-md);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-medium);
}

.distribution-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.distribution-name {
  font-weight: 500;
  color: var(--text-primary);
}

.distribution-count {
  font-size: 12px;
  color: var(--text-secondary);
}

.distribution-bar {
  height: 6px;
  background-color: var(--bg-tertiary);
  border-radius: 3px;
  overflow: hidden;
}

.distribution-fill {
  height: 100%;
  background-color: var(--color-primary);
  transition: width var(--duration-normal) var(--ease-out);
}

.distribution-percentage {
  font-size: 12px;
  color: var(--text-tertiary);
  text-align: right;
}

.empty-distribution {
  padding: var(--spacing-lg);
  text-align: center;
  background-color: var(--bg-secondary);
  border-radius: var(--radius-medium);
  border: 2px dashed var(--border-secondary);
}

.status-chart {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.chart-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.chart-segment {
  height: 20px;
  border-radius: 10px;
  min-width: 20px;
  transition: width var(--duration-normal) var(--ease-out);
}

.chart-segment--active {
  background-color: var(--color-success);
}

.chart-segment--inactive {
  background-color: var(--color-warning);
}

.chart-segment--suspended {
  background-color: var(--color-danger);
}

.chart-segment--locked {
  background-color: var(--apple-gray-3);
}

.chart-label {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: 12px;
  color: var(--text-secondary);
  min-width: 120px;
}

.chart-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.chart-color--active {
  background-color: var(--color-success);
}

.chart-color--inactive {
  background-color: var(--color-warning);
}

.chart-color--suspended {
  background-color: var(--color-danger);
}

.chart-color--locked {
  background-color: var(--apple-gray-3);
}

.apple-card__footer {
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .modal-overlay {
    padding: var(--spacing-md);
  }
  
  .large-dialog {
    max-height: 95vh;
  }
  
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .distribution-item {
    grid-template-columns: 1fr;
    text-align: center;
  }
  
  .chart-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .apple-card__footer {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .apple-card__footer .apple-button {
    width: 100%;
  }
}
</style>